<?php

namespace app\api\controller;

use app\lib\exception\ParameterException;

use app\common\Helper;
use app\common\lib\Wx;
use app\common\model\Storelabel;
use app\common\model\Storelabelconnect;
use app\common\model\Userfocus;
use app\common\model\Userinstore;
use app\common\model\Userinstorecount;
use app\common\model\Userreceivetic;
use app\common\model\Userstore;
use app\common\validate\IDMustBePostiveInt;
use app\common\validate\requestPaymentValidate;
use app\api\service\Pay;

use think\Db;
use think\Exception;
use think\Request;

class Common extends Base
{

    /**
     * 获取类型
     */
    public function getTypeName(Request $request){
        $param = $request->param();
        if(!$param['typeId']){
            return show(config('status.error_code'),'参数错误','参数错误');
        }
        $Type = \app\admin\model\Type::get($param['typeId']);
        if($Type){
            return show(config('status.success_code'),'ok',$Type);
        }else{
            return show(config('status.error_code'),'没找到数据','没找到数据');
        }
    }

    /**
     * 店铺搜索
     */
    public function searchStore(Request $request){
        $param = $request->param();
        /*if(empty($param['lat'])){
            return show(config('status.error_code'),'参数错误','lat 不能为空');
        }
        if(empty($param['lng'])){
            return show(config('status.error_code'),'参数错误','lng 不能为空');
        }*/
        if(empty($param['name'])){
            return show(config('status.error_code'),'参数错误','name 不能为空');
        }

        $StoreList = \app\admin\model\Store::where('status',1)->where('name','like','%'.$param['name'].'%')->select();
        if(!empty($StoreList)){
//            $stores = self::LatLngsort($param['lat'],$param['lng'],$StoreList);
//            return show(config('status.success_code'),'ok',$stores);

            foreach ($StoreList as &$item) {
                // 店铺标签
                $storeLabelIds = Storelabelconnect::where('storeId', $item['id'])->field('storeLabelId')->select();
                $storeLabelIds = array_column($storeLabelIds, 'storeLabelId');
                $storelabels = Storelabel::whereIn('id', $storeLabelIds)->field('storeLabel')->select();
                $item['storelabels'] = $storelabels;

                // 店铺券
                $ticket = Home::getTicket($item['id']);
                if($ticket){
                    $item['ticketId'] = $ticket['id'];
                    $item['ticketName'] = $ticket['name'];
                }
            }

            return show(config('status.success_code'),'ok',$StoreList);
        }else{
            return show(config('status.success_code'),'ok',[]);
        }
    }

    /**
     * 店铺关注/取消关注
     */
    public function focusStore(Request $request){
        $param = $request->param();
        if(empty($param['storeId']) || empty($param['userId'])){
            return show(config('status.error_code'),'参数错误','参数错误');
        }
        $where['userId'] = $param['userId'];
        $where['storeId'] = $param['storeId'];
        $Userfocus = Userfocus::where($where)->find();
        if(!$Userfocus){
            // 添加关注
            $UserfocusModel = new Userfocus();
            $UserfocusModel->userId = $param['userId'];
            $UserfocusModel->storeId = $param['storeId'];
            $UserfocusModel->focusTime = date('Y-m-d H:i:s',time());
            $UserfocusModel->save();

        }else{
            // 取消关注
            $Userfocus->delete();
        }

        return show(config('status.success_code'),'ok',1);
    }

    //进店数量统计
    public function addInStore(Request $request){
        $param = $request->param();
        if(empty($param['storeId']) || empty($param['userId'])){
            return show(config('status.error_code'),'参数错误','参数错误');
        }
        Db::startTrans();
        try{
            $Store = \app\admin\model\Store::get($param['storeId']);
            $Store->setInc('inStoreCount',1);
            $Userinstore = Userinstore::where(['storeId'=>$param['storeId'],'userId'=>$param['userId']])->find();
            if($Userinstore){
                $Userinstore->inStoreTime = date('Y-m-d H:i:s',time());
                $Userinstore->save();
                $Userinstore->setInc('inStoreCount',1);
            }else{
                $UserinstoreModel = new Userinstore();
                $UserinstoreModel->userId = $param['userId'];
                $UserinstoreModel->storeId = $param['storeId'];
                $UserinstoreModel->inStoreStatus = 1;
                $UserinstoreModel->inStoreCount = 1;
                $UserinstoreModel->inStoreTime = date('Y-m-d H:i:s',time());
                $UserinstoreModel->save();
            }
            $Userinstorecount = Userinstorecount::where(['storeId'=>$param['storeId'],'userId'=>$param['userId']])->whereTime('inStoreTime','today')->find();
            if($Userinstorecount){
                $Userinstorecount->setInc('inStoreCount',1);
            }else{
                $UserinstorecountModel = new Userinstorecount();
                $UserinstorecountModel->userId = $param['userId'];
                $UserinstorecountModel->storeId = $param['storeId'];
                $UserinstorecountModel->inStoreCount = 1;
                $UserinstorecountModel->inStoreTime = date('Y-m-d H:i:s',time());
                $UserinstorecountModel->save();
            }
            Db::commit();
            return show(config('status.success_code'),'ok',1);
        }catch (Exception $ex){
            Db::rollback();
        }
    }

    // 根据经纬度对店铺进行排序
    public static function LatLngsort($lat,$lng,$StoreList){
        $stores = [];
        for($i=0;$i<count($StoreList);$i++){
            $distance = (float)Helper::getDistance($lat,$lng,$StoreList[$i]);
            $res = Home::getinstoreAndcountFocus($StoreList[$i]['id']);
            $StoreList[$i]['countInStore'] = $res['countInStore'];
            $StoreList[$i]['countFocus'] = $res['countFocus'];
            $StoreList[$i]['distance'] = $distance;
            $Ticket = Home::getTicket($StoreList[$i]['id']);
            if($Ticket){
                $StoreList[$i]['Ticket'] = $Ticket['name'];
                $StoreList[$i]['TicketId'] = $Ticket['id'];
            }else{
                $StoreList[$i]['Ticket'] = '';
            }

            array_push($stores,$StoreList[$i]);
        }
        foreach ($stores as $k=>$v){
            $dos[$k] = $v['distance'];
        }
        array_multisort($dos, SORT_ASC, $stores);
        return $stores;
    }

    //用户支付入口
    public function requestPayment(Request $request){
        (new requestPaymentValidate())->goCheck();
        $param = $request->param();
        if(!$this->checkuser($param['userId'])){
            return show(config('status.ERROR_STATUS'),'用户不存在','用户不存在');
        }
        $Store = \app\admin\model\Store::get($param['storeId']);
        if($Store->status != 1){
            return show(config('status.ERROR_STATUS'),'店铺已经关闭','店铺已经关闭');
        }
        if($param['orderSource'] == 1){
            //购买优惠券
            //判断优惠券是否已经购买并且没有核销
            if(empty($param['ticketId'])){
                return show(config('status.ERROR_STATUS'),'缺少优惠券参数','缺少优惠券参数');
            }
            $check = $this->checkticket($param);
            if(!$check['pass']){
                if($check['status'] == 1000){
                    return show(config('status.ERROR_STATUS'),'此优惠券已过期','此优惠券已过期');
                }elseif ($check['status'] == 2000){
                    return show(config('status.ERROR_STATUS'),'您的限领次数已经用完，不能再领取','您的限领次数已经用完，不能再领取');
                }else{
                    return show(config('status.ERROR_STATUS'),'此优惠券售罄','此优惠券售罄');
                }
            }
        }elseif ($param['orderSource'] == 2){
            //使用优惠券付款
            if(empty($param['ticketId'])){
                return show(config('status.ERROR_STATUS'),'缺少优惠券参数','缺少优惠券参数');
            }
            if(empty($param['total_fee'])){
                return show(config('status.ERROR_STATUS'),'付款金额异常','付款金额异常');
            }
            if(empty($param['receiveticId'])){
                return show(config('status.ERROR_STATUS'),'参数异常','参数异常');
            }
            $Userreceivetic = Userreceivetic::get($param['receiveticId']);
            if($Userreceivetic){
                if($Userreceivetic->userId==$param['userId'] && $Userreceivetic->storeId == $param['storeId'] && $Userreceivetic->ticketId == $param['ticketId']){
                    if($Userreceivetic->status == 0){
                        $Ticket = \app\admin\model\Ticket::get($param['ticketId']);
                        $nowtime = date('Y-m-d H:i:s');
                        if($nowtime<$Ticket->beginTime){
                            return show(config('status.error_code'),'优惠活动还没开始','优惠活动还没开始');
                        }
                        if($nowtime>$Ticket->endTime){
                            return show(config('status.error_code'),'优惠券已经过期','优惠券已经过期');
                        }

                    }else{
                        return show(config('status.ERROR_STATUS'),'该券已经用过','该券已经用过');
                    }
                }else{
                    return show(config('status.ERROR_STATUS'),'核销用户异常','核销用户异常');
                }

            }else{
                return show(config('status.ERROR_STATUS'),'该券不存在','该券不存在');
            }

        }else{
            //todo
        }


        $pay = new Pay($param);
        return $pay->pay();

    }

    public function checkticket($param){
        $pass = [
            'status' => 1,
            'pass' => true
        ];
        $Ticket = \app\admin\model\Ticket::where(['id'=>$param['ticketId'],'status'=>5])->where('status',['=', 5], ['=', 4], ['=', 2],'or')->find();
        if(!$Ticket){
            throw new ParameterException([
                'msg' => '该活动不存在'
            ]);
        }else{
            if($Ticket->remainGross < 1){
                $pass['status'] = 3000;
                $pass['pass'] = false;
            }
        }

        if(date('Y-m-d H:i:s',time())>$Ticket->endTime){
            $pass['status'] = 1000;
            $pass['pass'] = false;
        }
        $Ticket = \app\admin\model\Ticket::get($param['ticketId']);
        $Userreceivetic = Userreceivetic::where(['userId'=>$param['userId'],'ticketId'=>$param['ticketId']])->select();
        $count = count($Userreceivetic);
        if($Ticket->limitGross<=$count){
            $pass['status'] = 2000;
            $pass['pass'] = false;
        }
        return $pass;
    }

    private function checkuser($userId){
        $User = \app\admin\model\User::get($userId);
        if($User){
            return true;
        }
        return false;
    }


    //生成店铺二维码
    public function getStoreCode($id = ''){
        (new IDMustBePostiveInt())->goCheck();


        $Store = \app\admin\model\Store::get($id);
        if($Store){
            if($Store->qrCode){
                return show(config('status.SUCCESS_STATUS'),'获取二维码成功',$Store->qrCode);
            }
            $res = Wx::getStoreCode($id);
            $Store->qrCode = $res;
            $Store->save();
            return show(config('status.SUCCESS_STATUS'),'获取二维码成功',$res);
        }else{
            return show(config('status.ERROR_STATUS'),'该店铺不存在','该店铺不存在');
        }


    }
    //判断我是否有店铺
    public function MyisthereanyStore(Request $request){
        $param = $request->param();
        if(!empty($param['userId'])){
            $User = \app\admin\model\User::get($param['userId']);
            if($User){
                $Userstore = Userstore::where('userId',$param['userId'])->find();
                if(!$Userstore){
                    return show(2,'暂无店铺',null);
                }else{
                    return show(config('status.success_code'),'ok','ok');
                }
            }else{
                return show(config('status.error_code'),'用户信息异常','用户信息异常');
            }

        }else{
            return show(config('status.error_code'),'参数错误','参数错误');
        }

    }
    public function getStoreStatus(Request $request){
        $param = $request->param();
        if(empty($param['storeId'])){
            return show(config('status.error_code'),'参数错误','参数错误');
        }
        $Store = \app\admin\model\Store::get($param['storeId']);
        if($Store){
            return show(config('status.success_code'),'ok',$Store->status);
        }else{
            return show(config('status.error_code'),'店铺不存在','店铺不存在');
        }

    }
}